package com.eqdd.yiqidian.ui.tongxunlu;

import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eqdd.yiqidian.AddGroupChatActivityCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.FloatingItemDecoration;
import com.eqdd.yiqidian.adapter.listadapter.BaseAdapterHelper;
import com.eqdd.yiqidian.adapter.listadapter.QuickAdapter;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.bean.BaseBean;
import com.eqdd.yiqidian.bean.rebuild.FriendListResultBean;
import com.eqdd.yiqidian.bean.rebuild.GroupListResultBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpPresneter;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.listener.OnMyCheckedChangeListener;
import com.eqdd.yiqidian.utils.DensityUtil;
import com.eqdd.yiqidian.utils.GreenDaoUtil;
import com.eqdd.yiqidian.utils.GsonUtils;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ItemDecorationUtil;
import com.eqdd.yiqidian.utils.PinYinUtil;
import com.eqdd.yiqidian.utils.SideBarUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.rong.imkit.RongIM;
import rx.android.schedulers.AndroidSchedulers;

public class AddGroupChatActivity extends BaseActivity {


    private List<FriendListResultBean> allUserList;// 好友列表
    private List<FriendListResultBean> selectList = new ArrayList<>();// 好友列表

    int total = 0;
    private AddGroupChatActivityCustom dataBinding;
    private SlimAdapterEx<FriendListResultBean> slimAdapterEx;
    private FloatingItemDecoration itemDecoration;
    private SlimAdapterEx slimAdapterExHead;


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_group_chat);
        initTopTitleBar(View.VISIBLE, "创建群");

    }

    @Override
    public void initData() {
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        itemDecoration = ItemDecorationUtil.openFloatDeco(this, dataBinding.recyclerView);
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.contact_item, new SlimInjector<FriendListResultBean>() {
            @Override
            public void onInject(FriendListResultBean data, IViewInjector injector) {

                injector.checked(R.id.checkbox, data.isCheck())
                        .text(R.id.tv_right, data.getUpname())
                        .imageCircle(R.id.iv_head, data.getIphoto());
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {
                    FriendListResultBean dataItem = slimAdapterEx.getDataItem(position);
                    dataItem.setCheck(!dataItem.isCheck());
                    if (dataItem.isCheck()) {
                        selectList.add(dataItem);
                        showCheckImage(dataItem);
                    } else {
                        deleteImage(dataItem);
                        selectList.remove(dataItem);
                    }
                    slimAdapterEx.notifyItemChanged(position);
                });
        dataBinding.recyclerViewHead.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        slimAdapterExHead = SlimAdapterEx.create().register(R.layout.list_item_59, new SlimInjector<FriendListResultBean>() {
            @Override
            public void onInject(FriendListResultBean data, IViewInjector injector) {
                injector.imageCircle(R.id.iv_head, data.getIphoto());
            }
        }).attachTo(dataBinding.recyclerViewHead).updateData(selectList);
        dataBinding.waveSideBar.setRecyclerView(dataBinding.recyclerView);
    }

    @Override
    public void setView() {
        OkGo.<HttpResult<List<FriendListResultBean>>>post(HttpConfig.BASE_URL + HttpConfig.FRIEND_LIST_INFO)
                .params("userGuid", user.getGuid())
                .execute(new DialogCallBack<HttpResult<List<FriendListResultBean>>>(AddGroupChatActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<FriendListResultBean>>> response) {
                        HttpResult<List<FriendListResultBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            Collections.sort(httpResult.getItems());
                            allUserList = httpResult.getItems();
                            updateView(httpResult.getItems());
                        }
                    }
                });
        dataBinding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(s)) {
                    updateView(allUserList);
                } else {
                    ArrayList<FriendListResultBean> temp = new ArrayList<>();
                    Flowable.fromIterable(allUserList)
                            .filter(bean -> bean.getUpname().contains(s) || bean.getUname().contains(s))
                            .subscribe(temp::add, System.out::println, () -> {
                                updateView(temp);
                            });
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        dataBinding.includeChatTitle.txtRight.setText("确定");
        dataBinding.includeChatTitle.txtRight.setTextColor(0xFF45C01A);
        TextView mDialogText = (TextView) LayoutInflater.from(this).inflate(
                R.layout.list_position, null);
        mDialogText.setVisibility(View.INVISIBLE);

        RxView.clicks(dataBinding.includeChatTitle.txtRight)
                .throttleFirst(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe((i) -> {
                            String groupid = (new Date().getTime() / 1000) + "" + user.getUname();
                            new HttpPresneter.Builder(HttpConfig.CREATE_GROUP, String.class, AddGroupChatActivity.this)
                                    .Params("userid", user.getGuid())
                                    .Params("GroupMembers", createUid())
                                    .Params("groupid", groupid)
                                    .Params("groupname", TextUtils.isEmpty(dataBinding.etQunName.getText()) ? "未命名" : dataBinding.etQunName.getText().toString().trim())
                                    .setOnHttpListener(new HttpPresneter.OnHttpListener() {
                                        @Override
                                        public void onError(Throwable e) {

                                        }

                                        @Override
                                        public void onNext(Object o) {
                                            GroupListResultBean groupBean = new GroupListResultBean();
                                            groupBean.setGroupid(groupid);
                                            groupBean.setGroupname(TextUtils.isEmpty(dataBinding.etQunName.getText()) ? "未命名" : dataBinding.etQunName.getText().toString().trim());
                                            GreenDaoUtil.insertGroup(groupBean);
                                            RongIM.getInstance().startGroupChat(AddGroupChatActivity.this, groupid, TextUtils.isEmpty(dataBinding.etQunName.getText()) ? "未命名" : dataBinding.etQunName.getText().toString().trim());
                                        }
                                    })
                                    .build()
                                    .post();
                        }
                );
    }

    private void updateView(List<FriendListResultBean> data) {
        slimAdapterEx.updateData(data);
        ItemDecorationUtil.updateData(itemDecoration, data, "upname");
        SideBarUtil.updateData(dataBinding.waveSideBar, data, "upname");
    }

    private String createUid() {
        StringBuilder uid = new StringBuilder(";" + user.getGuid());
        for (FriendListResultBean s : selectList) {
            uid.append(";").append(s.getGuid());
        }
        return uid.toString();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_header:
                // TODO 打开群列表
                startActivity(TeamCheatListActivity.class);
                break;
            default:
                break;
        }
    }


    // 即时显示被选中用户的头像和昵称。
    private void showCheckImage(FriendListResultBean bean) {

        total++;
        slimAdapterExHead.notifyItemInserted(selectList.indexOf(bean));
        dataBinding.includeChatTitle.txtRight.setText("确定(" + total + ")");
        if (total > 0) {
            if (dataBinding.ivSearch.getVisibility() == View.VISIBLE) {
                dataBinding.ivSearch.setVisibility(View.GONE);
            }
        }
    }

    private void deleteImage(FriendListResultBean bean) {
        slimAdapterExHead.notifyItemRemoved(selectList.indexOf(bean));
        total--;
        dataBinding.includeChatTitle.txtRight.setText("确定(" + total + ")");
        if (total < 1) {
            if (dataBinding.ivSearch.getVisibility() == View.GONE) {
                dataBinding.ivSearch.setVisibility(View.VISIBLE);
            }
        }
    }

}
